import React, { useState, useEffect } from 'react';
import { Badge, Button, Checkbox, Form, Input, Modal, Row, Select, Space, Table, message } from 'antd';
import PageTitle from '@/components/pageTitle';
import Icon from '@/components/layout/Icon';
import MyModal from '@/components/modal';
import usePagination, { useHeight } from '@/utils/hooks/pagination';
import { getUserMangeList, deleteUser } from '@/request/userMange';
import { roleOptions, userStatusOptions, roleText, status, statusColor } from '@/utils/config/userManageConfig';

import styles from './index.module.css';
import AddUserModal from './components/AddUserModal';
import ResetPassWord from './components/ResetPassWord';

const layout = {
  labelCol: { flex: '70px' },
  wrapperCol: { flex: '200px' },
};

export default function UserManage() {
  const [form] = Form.useForm();
  const [actionInfo, setActionInfo] = useState<any>({});
  const [searchParams, setSearchParams] = useState({});
  const [open, setOpen] = useState(false);
  const [resetPassWord, setResetPassWord] = useState(false); // 重置密码
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const { height } = useHeight(300);
  const { pagination, setPagination, onChange } = usePagination({
    pageSize: 10,
  });

  const handleSearch = async (params) => {
    setLoading(true);
    try {
      const res: any = await getUserMangeList(params);
      if (res) {
        setData(res.data);
        setPagination({
          ...pagination,
          total: res.total,
        });
        setLoading(false);
      }
    } catch (err: any) {
      setLoading(false);
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  // 编辑
  const onEdit = (it) => {
    setActionInfo({ ...it, title: '编辑用户' });
    setOpen(true);
  };

  // 删除
  const onDelete = (it) => {
    setActionInfo(it);
    setDeleteOpen(true);
  };

  // 确定删除
  const onConfirmDelete = async () => {
    try {
      const res = await deleteUser({ personId: actionInfo?._id || '', isDelete: actionInfo?.isDelete === 1 ? 0 : 1 });
      if (res) {
        message.success('操作成功');
        setDeleteOpen(false);
        handleSearch({ ...searchParams, page: 1, pageSize: pagination.pageSize });
      }
    } catch (err: any) {
      message.warning(err.message);
    }
  };

  // 重置密码
  const onResetPassWord = (it) => {
    setResetPassWord(true);
    setActionInfo({ ...it });
  };

  const columns: any = [
    {
      dataIndex: 'userName',
      title: '用户名称',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'name',
      title: '姓名',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'phone',
      title: '手机号',
      align: 'center',
      width: 150,
    },
    {
      dataIndex: 'role',
      title: '角色',
      align: 'center',
      width: 120,
      render: (text) => roleText[text] || '-',
    },
    {
      dataIndex: 'isDelete',
      title: '状态',
      align: 'center',
      width: 80,
      render: (text) => <Badge color={statusColor[text]} text={status[text]} /> || '-',
    },
    {
      dataIndex: 'gmtCreated',
      title: '创建时间',
      align: 'center',
      width: 160,
    },
    {
      dataIndex: 'updateTime',
      title: '更新时间',
      align: 'center',
      width: 160,
    },
    {
      dataIndex: 'action',
      title: '操作',
      align: 'left',
      width: 150,
      render: (_, it) => {
        return (
          <Space>
            <span className="tableActionBtn" onClick={() => onEdit(it)}>
              编辑
            </span>
            {it.isDelete === 1 ? (
              <span className="tableActionBtn" onClick={() => onDelete(it)}>
                启用
              </span>
            ) : null}
            {it.isDelete === 0 ? (
              <span className="tableActionBtn" onClick={() => onDelete(it)}>
                停用
              </span>
            ) : null}
            {it.isDelete === 0 ? (
              <span className="tableActionBtn" onClick={() => onResetPassWord(it)}>
                重置密码
              </span>
            ) : null}
          </Space>
        );
      },
    },
  ];

  const handleChange = (page: any) => {
    const p = pagination.pageSize !== page.pageSize ? 1 : page.current;
    onChange(page);
    handleSearch({
      ...searchParams,
      page: p,
      pageSize: page.pageSize,
    });
  };

  // 搜索
  const onSearch = (values) => {
    setPagination({
      ...pagination,
      current: 1,
      pageSize: pagination.pageSize,
    });
    setSearchParams(values);
  };

  // 重置
  const onReset = () => {
    setSearchParams({});
    form.resetFields();
  };

  // 关闭弹窗
  const handleClose = () => {
    setOpen(false);
    setActionInfo({});
  };

  // 关闭重置密码弹框
  const handleCloseResetPassWord = () => {
    setResetPassWord(false);
    setActionInfo({});
  };

  // 新增
  const handleAdd = () => {
    setOpen(true);
    setActionInfo({
      title: '新增用户',
    });
  };

  useEffect(() => {
    if (!open && !resetPassWord) {
      handleSearch({ ...searchParams, page: pagination.current, pageSize: pagination.pageSize });
      setActionInfo({});
    }
  }, [searchParams, open, resetPassWord]);

  return (
    <div className={styles.userMange}>
      <PageTitle title="用户管理" />
      <Form form={form} onFinish={onSearch} layout="inline" colon={false}>
        <Form.Item name="name" label="用户名称" {...layout}>
          <Input placeholder="请输入操作人" allowClear style={{ width: '200px' }} />
        </Form.Item>
        <Form.Item name="role" label="角色" {...layout} style={{ marginRight: 50, marginBottom: '10px' }}>
          <Select placeholder="请选择" style={{ width: '200px' }} options={roleOptions} />
        </Form.Item>
        <Form.Item name="isDelete" label="用户状态" {...layout} style={{ marginRight: 50, marginBottom: '10px' }}>
          <Select placeholder="请选择" style={{ width: '200px' }} options={userStatusOptions} />
        </Form.Item>
        <Form.Item>
          <Button onClick={onReset} style={{ marginRight: '10px' }}>
            重 置
          </Button>
          <Button
            type="primary"
            style={{ marginRight: '44px' }}
            htmlType="submit"
            icon={<Icon src="/images/search.png" width={16} height={16} style={{ marginRight: '4px', verticalAlign: 'text-top' }} />}
          >
            查 询
          </Button>
        </Form.Item>
        <Form.Item style={{ flex: '1', display: 'flex', justifyContent: 'flex-end', marginRight: '0' }}>
          <Button onClick={handleAdd} className="flex" type="primary" icon={<Icon src="/images/add.png" width={16} height={16} style={{ marginRight: '4px' }} />} style={{ marginBottom: '20px' }}>
            添加
          </Button>
        </Form.Item>
      </Form>
      <Table dataSource={data} columns={columns} scroll={{ y: height }} rowKey="_id" loading={loading} onChange={handleChange} pagination={pagination}></Table>
      <AddUserModal open={open} actionInfo={actionInfo} handleClose={handleClose} />
      <ResetPassWord open={resetPassWord} actionInfo={actionInfo} handleClose={handleCloseResetPassWord} />
      <MyModal
        destroyOnClose
        title="提示"
        open={deleteOpen}
        width={600}
        onCancel={() => {
          setDeleteOpen(false);
          setActionInfo({});
        }}
        onOk={() => {
          onConfirmDelete();
        }}
      >
        <div>{`确认${actionInfo?.isDelete === 0 ? '停用' : '启用'}用户名为“${(actionInfo?.userName as string) || '-'}”吗？`}</div>
      </MyModal>
    </div>
  );
}
